<!-- BP2 血压仪设备 -->
<template>
	<view class="pageview">
		<firstConnect v-if="isFirst" :device-type="deviceType" :deviceStatus="deviceStatus" @startUse="startUse" @retry="retry"></firstConnect>
		<template v-else>
			<view class="toptip flex align-center justify-between" v-if="!isConnected">
				<text>{{ blueState ? '当前设备未连接，请连接设备' : '需要开启蓝牙，连接设备' }}</text>
				<view class="btn flex align-center" @click="devicesDiscovery" v-if="blueState">
					<u-loading-icon color="#fff" :show="deviceStatus == 0 || deviceStatus == 1"></u-loading-icon>
					<text>去连接</text>
				</view>
			</view>
			<view class="startWork">
				<bpChart ref="bpChart"></bpChart>
				<view v-if="isConnected && deviceRunStatus == 5">
					<view class="tip">{{ deviceData.systolic_pressure > 0 ? '本次测量数据已保存' : '测量失败' }}</view>
					<!-- <u-button shape="circle" type="primary" text="重新测量" @click="resume"></u-button> -->
					<template v-if="deviceData.systolic_pressure > 0">
						<view class="stepbox">
							<bpStep size="lg" :systolic_pressure="deviceData.systolic_pressure" :diastolic_pressure="deviceData.diastolic_pressure"></bpStep>
						</view>
						<view class="flex result">
							<view class="flex-sub item">
								<view>收缩压</view>
								<view class="u-margin-top-20">
									<text class="num">{{ deviceData.systolic_pressure }}</text>
									<text class="unit">mmHg</text>
								</view>
							</view>
							<view class="flex-sub item">
								<view>舒张压</view>
								<view class="u-margin-top-20">
									<text class="num">{{ deviceData.diastolic_pressure }}</text>
									<text class="unit">mmHg</text>
								</view>
							</view>
							<view class="flex-sub item">
								<view>心率</view>
								<view class="u-margin-top-20">
									<text class="num">{{ deviceData.hr }}</text>
									<text class="unit">次/分钟</text>
								</view>
							</view>
						</view>
					</template>
					<view class="tip u-m-t-20">点击血压仪上启动键，重新开始测量</view>
				</view>
			</view>
		</template>
	</view>
</template>

<script>
import { ab2str, formatNum, formatSecond, chunk } from '@/utils/util';
const fs = wx.getFileSystemManager();
const BP2Protocol = require('@/utils/ble_devices/bp2');
const BP2Builder = {
	// 注意这里的this是实例化后的BP2对象，而不是page
	notifyServiceId: '14839AC4-7D7E-415C-9A42-167340CF2339',
	deviceFoundFilter: item => /(BP2)/.test(item.name),
	connectionStateChange: res => console.log('BP2连接状态改变', res),
	characteristicValueChange: function (res) {
		if (res.value) {
			// console.log('这里是原始数据', res.value);
			// 开始解析数据
			if (res.value !== this.oldCallbackData) {
				//可能会有重复的包
				this.oldCallbackData = res.value;
				// 而且微信返回的value是ArrayBuffer，所以同样要先转换成str
				this.parseData(ab2str(res.value));
			}
		}
	}
};

const BP2 = new BP2Protocol(BP2Builder);
let foundTimer = null;
import firstConnect from './components/firstConnect';
import bpChart from './components/bpChart';
import stompMixin from '@/common/stompMixin.js';
import bpStep from '@/components/bpStep';
import { mapState } from 'vuex';
export default {
	data() {
		return {
			isConnected: false, // 是否连接设备
			devicesDiscovered: [], // 设备列表
			connectedDevice: null, // 当前连接设备
			deviceType: 'BP2',
			deviceTypeId: '',
			isFirst: true,
			deviceStatus: 0,
			deviceData: {
				runStatus: 0
			},
			blueState: false,
			deviceRunStatus: -1, //0关机，1数据回顾，2充电，3开机预备，4血压测量中，5血压测量结束，6心电测量中，7心电测量结束
			hasSave: 0
		};
	},
	mixins: [stompMixin],
	computed: {
		...mapState(['userInfo', 'curAccount'])
	},
	components: {
		firstConnect,
		bpChart,
		bpStep
	},
	onLoad(optioin) {
		this.deviceType = optioin.deviceType;
		if (optioin.deviceTypeId) {
			this.deviceTypeId = optioin.deviceTypeId;
			this.isFirst = true;
		} else {
			this.deviceMac = optioin.deviceMac;
			this.isFirst = false;
		}
		// 使用 watch 方法监听 message 属性的变化
		const appInstance = getApp();
		appInstance.watch(this, BP2, {
			//蓝牙配置状态
			adapterState: function (newVal) {
				if (newVal && !this.blueState) {
					this.blueState = true; //设置蓝牙初始化成功了
					this.deviceStatus = -1;
					if (this.isFirst) {
						this.devicesDiscovery();
					}
				}
			},
			foundDevices: function (newVal) {
				this.devicesDiscovered = newVal;
				if (this.devicesDiscovered.length > 0 && !this.isConnected) {
					let index = -1;
					if (this.deviceMac) {
						index = this.devicesDiscovered.findIndex(item => item.deviceId == this.deviceMac);
					} else {
						index = this.devicesDiscovered.findIndex(item => /(BP2A)/.test(item.name));
					}
					console.log('index', index);
					if (index > -1) {
						this.deviceStatus = 1;
						this.connectToDevice(index);
						clearTimeout(foundTimer);
						foundTimer = null;
					}
				}
			},
			connectedDevice: function (newVal) {
				console.log('newVal', newVal);
				this.isConnected = !!newVal;
				this.connectedDevice = newVal;
				this.deviceStatus = 2;
				if (this.isFirst) {
					this.addDevice();
				} else {
					this.getRealTimeEcg();
				}
			},
			deviceRunInfo: function (newVal, oldVal) {
				this.deviceData = newVal;
				if (newVal && JSON.stringify(newVal) != JSON.stringify(oldVal)) {
					if (this.deviceRunStatus == 5 && this.hasSave == 0) {
						this.handleDeviceRunInfo(newVal);
					}
					if (this.deviceData.runStatus == 0) {
						this.$refs.bpChart && this.$refs.bpChart.getServerData(newVal.pressure);
					}
				}
			},
			deviceRunStatus: function (newVal, oldVal) {
				//第一次开始就检测到了结束，不处理
				if (newVal == 5 && this.deviceRunStatus == -1) {
					return;
				}
				this.deviceRunStatus = newVal;
				if (this.deviceRunStatus == 3) {
					this.deviceData.pressure = 0;
					this.hasSave = 0;
				}
			}
		});
		// 开启监听ER2属性
		// this.watchER2()
		// 初始化蓝牙
		BP2.init();
	},
	onUnload() {
		// 不在当前页面的时候断开连接
		this.disconnectToDevice();
		// 关闭实时指令timer
		this.stopRealTimeEcg();
		if (foundTimer || this.deviceStatus == 0) {
			this.clearfoundTimer();
		}
	},

	methods: {
		// 搜索周围设备
		devicesDiscovery() {
			this.deviceStatus = 0;
			BP2.startDevicesDiscovery();
			//5s没有找到设备，就提示没有发现设备
			foundTimer = setTimeout(() => {
				this.clearfoundTimer();
			}, 5000);
		},
		// 连接指定设备
		connectToDevice(index) {
			BP2.stopDevicesDiscovery();
			const targetDevice = this.devicesDiscovered[index];
			BP2.connectToDevice(targetDevice).then(() => {
				// 连接成功后获取设备信息
				const cmd = BP2.generateCmd('e1', '00', '');
				BP2.writeValue(cmd);
			});
		},
		// 断开当前连接设备
		disconnectToDevice() {
			BP2.disconnectToDevice();
		},

		getRealTimeEcg() {
			if (!BP2.EcgCmdTimer) {
				BP2.EcgCmdTimer = setInterval(() => {
					const EcgCmd = BP2.generateCmd('08', '00', ''); // BP2实时的指令是08，type是00，data是空，由于指令有流水号，所以每次都要重新生成
					BP2.writeValue(EcgCmd);
					// if (this.deviceData.runStatus == 1) {
					// 	//测量完成
					// 	this.stopRealTimeEcg();
					// }
				}, 500);
			}
		},
		// 停止实时监听
		stopRealTimeEcg() {
			if (BP2.EcgCmdTimer) {
				clearInterval(BP2.EcgCmdTimer);
				BP2.EcgCmdTimer = null;
			}
		},
		handleDeviceRunInfo(deviceRunInfo) {
			switch (deviceRunInfo.runStatus) {
				case 0: // 血压中
					// this.setData({
					// 	runStatus: deviceRunInfo.runStatus,
					// 	pressure: deviceRunInfo.pressure,
					// 	hr: deviceRunInfo.hr,
					// 	isPressDone: false
					// })
					break;
				case 1: // 血压结束
					if (deviceRunInfo.systolic_pressure > 0) {
						console.log('需要保存', deviceRunInfo);
						this.hasSave = 1; //已经保存过了
						this.send(
							JSON.stringify({
								detailId: this.curAccount.detailId,
								type: this.deviceType,
								data: deviceRunInfo
							})
						);
					}

					break;
			}
		},
		//重新开始测量
		resume() {
			this.deviceData.pressure = 0;
			this.deviceData.runStatus = 0;
			//this.getRealTimeEcg();
		},
		startUse() {
			this.isFirst = false;
			this.getRealTimeEcg();
		},
		retry() {
			this.deviceStatus = 0;
			this.devicesDiscovery();
		},
		addDevice() {
			this.$postAction(this.$deviceapi.addDevice, {
				bindState: 1,
				deviceTypeId: this.deviceTypeId,
				userId: this.userInfo.userId,
				devName: this.connectedDevice.name,
				mac: this.connectedDevice.deviceId
			});
		},
		clearfoundTimer() {
			BP2.stopDevicesDiscovery();
			clearTimeout(foundTimer);
			foundTimer = null;
			this.deviceStatus = 3;
		},
		
	}
};
</script>

<style scoped lang="scss">
.pageview {
	background: #f2f2f2;
	height: 100vh;
	overflow: auto;
}

.startWork {
	width: 600upx;
	margin: 0 auto;
	padding-top: 180upx;

	.imgbox {
		width: 400upx;
		margin: 0 auto 70upx;
	}

	.tip {
		text-align: center;
		margin-bottom: 10upx;
	}

	.stepbox {
		margin-top: 50upx;
	}

	.result {
		background: #fff;
		border-radius: 16upx;
		font-size: 28upx;
		color: #a5adae;
		padding: 30upx 20upx;
		margin-top: 50upx;

		.item {
			padding: 0 16upx;
		}

		.num {
			color: #243138;
			font-size: 46upx;
			font-weight: bold;
		}

		.unit {
			color: #374547;
			font-size: 24upx;
			margin-left: 10upx;
		}
	}
}

.toptip {
	background: #fff;
	padding: 20upx;
	position: absolute;
	top: 0;
	left: 0;
	right: 0;

	.btn {
		background: $u-primary;
		padding: 0 20upx;
		color: #fff;
		border-radius: 50upx;
		line-height: 60upx;
	}
}
</style>
